import { useState, useEffect } from 'react';
import { Form, Table, Row, Input, Pagination, Modal } from 'antd';
import { axconst } from '@/shared/axconst';
import AxModal from '@/components/AxForm/AxModal/index';
import { AxEditableContext, AxEditableFormRow, AxEditableCellSimple } from '../AxFormItem';
import { AxColumnTime } from '@/components/AxList';
import AxColumnAction from '@/components/AxList/AxColumnAction';

const { Search } = Input;
/**
 * 自定义选择冲抵
 * @param title 表单名称
 * @param placeholder 占位符
 * @param visible 可见性
 * @param handleVisible 可见性处理函数
 * @param handleRead 选项数据读取函数
 * @param handleCreate 添加处理函数
 */
const AxSelectOffset = props => {
  const {
    placeholder,
    selectedData: selectedDataFromProps,
    handleRead: handleReadFromProps,
    handleCreate: handleCreateFromProps,
    handleVisible,
    ...rest
  } = props;
  const [data, setData] = useState({
    list: [],
    pagination: {},
  });
  const [selectedData, setSelectedData] = useState({
    list: [],
    pagination: {},
  });
  const [loading, setLoading] = useState(false);
  /** 收费项目经费编辑key */
  const [editingKey, setEditingKey] = useState(null);
  /** 收费项目经费编辑record */
  const [editingRecord, setEditingRecord] = useState(null);
  /** 查询字段 */
  let field = {};
  /** 分页初始值 */
  let page = axconst.page.params;

  useEffect(() => {
    setSelectedData({ list: [...selectedDataFromProps] || [] });
  }, [selectedDataFromProps]);

  /** 搜索 */
  const handleSearch = val => {
    if (val && val.trim() !== '') {
      field['searchFeeString'] = val.trim();
    } else {
      field = {};
    }
    return handleRead();
  };

  /** 读取数据 */
  const handleRead = () => {
    if (handleReadFromProps) {
      setLoading(true);
      return handleReadFromProps(page, field).then(res => {
        res.list.forEach(i => {
          const idx = selectedData.list.findIndex(j => i.id === j.id);
          i.setMoney = 0;
          if (idx > -1) i.setMoney = selectedData.list[idx].setMoney;
        });
        setData(res);
        setLoading(false);
      });
    }
  };

  /** 保存数据 */
  const handleCreate = () => {
    if (handleCreateFromProps)
      return handleCreateFromProps(selectedData.list).then(res => {
        if (handleVisible) handleVisible();
      });
  };

  /** 改变分页 */
  const handlePageChange = (currentPage, pageSize) => {
    page = {
      currentPage,
      pageSize,
    };
    handleRead();
  };

  /** 标记修改行 */
  const isEditing = record => record.id === editingKey;

  /** 取消 */
  const cancel = e => {
    if (e) e.stopPropagation();
    setEditingKey(null);
    setEditingRecord(null);
  };

  /** 修改 */
  const update = record => {
    setEditingKey(record.id);
    setEditingRecord(record);
  };

  /** 保存冲抵金额到行数据上 */
  const save = (e, form, row) => {
    form.validateFields((error, v) => {
      if (error) {
        return;
      }

      const idx = data.list.findIndex(item => row.id === item.id);
      const newData = { ...row, setMoney: v.setMoney };
      data.list[idx] = newData;

      const idxSelected = selectedData.list.findIndex(item => row.id === item.id);
      if (idxSelected > -1) {
        selectedData.list[idxSelected] = newData;
      } else {
        selectedData.list.push(data.list[idx]);
      }
      setData({ ...data, list: data.list });
      setSelectedData({ ...selectedData, list: selectedData.list });
      setEditingKey(null);
    });
  };

  /** 单击修改 */
  const handleClick = record => {
    if (update) {
      update(record);
    }
  };

  /** 本次冲抵输入验证 */
  const validator = (rule, value, callback) => {
    rule.label = '充抵金额';
    try {
      if (value === null || value === undefined || value === '') {
        throw new Error(`${rule.label}不能为空`);
      }
      if (parseFloat(value) <= 0) {
        throw new Error(`${rule.label}需大于0`);
      }
      if (value && editingRecord) {
        if (parseFloat(value) > (editingRecord.canMoney || 0)) {
          throw new Error(`${rule.label}不能大于可用金额`);
        }
      }
      if (rule.pattern && rule.pattern.reg && value) {
        if (!new RegExp(rule.pattern.reg).test(value)) {
          if (rule.pattern.message) {
            throw new Error(rule.pattern.message);
          }
          throw new Error(`${rule.label}格式不正确`);
        }
      }
      callback(); // 通过验证
    } catch (err) {
      callback(err);
    }
  };

  /** 待选列表列 */
  let columns = [
    {
      title: '充抵金额',
      dataIndex: 'setMoney',
      width: axconst.width.long,
      ellipsis: true,
      editable: true,
    },
    {
      title: '可用金额',
      dataIndex: 'canMoney',
      width: axconst.width.fouronly,
      ellipsis: true,
      render: (val, record) => {
        return val - record.setMoney;
      },
    },
    {
      title: '凭证号',
      dataIndex: 'voucherNum',
      width: axconst.width.voucheronly,
      ellipsis: true,
    },
    {
      title: '票据号',
      dataIndex: 'noteNum',
      width: axconst.width.bill,
      ellipsis: true,
    },
    {
      title: '校区',
      dataIndex: 'campusName',
      width: axconst.width.fouronly,
      ellipsis: true,
    },
    {
      title: '姓名',
      dataIndex: 'customerName',
      width: axconst.width.threeonly,
      ellipsis: true,
    },
    {
      title: '身份证',
      dataIndex: 'idcard',
      width: axconst.width.idcard,
      ellipsis: true,
    },
    {
      title: '缴费内容',
      dataIndex: 'name',
      width: axconst.width.long,
      ellipsis: true,
    },
    {
      title: '缴费项',
      dataIndex: 'itemName',
      width: axconst.width.five,
      ellipsis: true,
    },
    {
      title: '缴费日期',
      dataIndex: 'feeDate',
      width: axconst.width.times,
      ellipsis: true,
      render: val => <AxColumnTime format="yyyy-MM-dd" value={val} />,
    },
  ];

  columns = columns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      onCell: record => ({
        record,
        editable: col.editable,
        required: col.required,
        enumName: col.enumName,
        dataIndex: col.dataIndex,
        title: col.title,
        data: col.data,
        pattern: col.pattern,
        // columnsNoChange: columnsNoChange,
        showValueWrap: true,
        autoFocus: true,
        cellType: 'number',
        editing: isEditing(record),
        validator: validator,
        save: save,
      }),
      ...col,
    };
  });

  columns.push({
    title: '操作',
    width: axconst.width.three,
    fixed: 'right',
    render: (text, record) => {
      const editable = isEditing(record);
      const disabled = editingKey !== null;
      return editable ? (
        <span>
          <AxEditableContext.Consumer>
            {form => (
              <a onClick={e => save(e, form, record)} style={{ marginRight: 8 }}>
                保存
              </a>
            )}
          </AxEditableContext.Consumer>
        </span>
      ) : (
        <AxColumnAction
          buttons={[
            {
              text: '冲抵',
              onClick: () => update(record),
            },
          ]}
        />
      );
    },
  });

  /** 已选列表列 */
  const selectedColumns = [
    {
      title: '充抵金额',
      dataIndex: 'setMoney',
      width: axconst.width.long,
      ellipsis: true,
    },
    {
      title: '可用金额',
      dataIndex: 'canMoney',
      width: axconst.width.fouronly,
      ellipsis: true,
      render: (val, record) => {
        return val - record.setMoney;
      },
    },
    {
      title: '凭证号',
      dataIndex: 'voucherNum',
      width: axconst.width.voucheronly,
      ellipsis: true,
    },
    {
      title: '票据号',
      dataIndex: 'noteNum',
      width: axconst.width.bill,
      ellipsis: true,
    },
    {
      title: '校区',
      dataIndex: 'campusName',
      width: axconst.width.fouronly,
      ellipsis: true,
    },
    {
      title: '姓名',
      dataIndex: 'customerName',
      width: axconst.width.threeonly,
      ellipsis: true,
    },
    {
      title: '身份证',
      dataIndex: 'idcard',
      width: axconst.width.idcard,
      ellipsis: true,
    },
    {
      title: '缴费内容',
      dataIndex: 'name',
      width: axconst.width.long,
      ellipsis: true,
    },
    {
      title: '缴费项',
      dataIndex: 'itemName',
      width: axconst.width.five,
      ellipsis: true,
    },
    {
      title: '缴费日期',
      dataIndex: 'feeDate',
      width: axconst.width.times,
      ellipsis: true,
      render: val => <AxColumnTime format="yyyy-MM-dd" value={val} />,
    },
    {
      title: '操作',
      width: axconst.width.three,
      fixed: 'right',
      render: (text, record) => {
        return (
          <AxColumnAction
            buttons={[
              {
                text: '删除',
                onClick: () => handleRemoveSelectedData(record),
              },
            ]}
          />
        );
      },
    },
  ];

  /** 移除已选冲抵项 */
  const handleRemoveSelectedData = record => {
    const idx = selectedData.list.findIndex(item => record.id === item.id);
    if (idx > -1) {
      selectedData.list.splice(idx, 1);
      setSelectedData({ ...selectedData, list: selectedData.list });
    }

    /** 改变被选冲抵项金额 */
    const dataIdx = data.list.findIndex(item => record.id === item.id);
    if (dataIdx > -1) {
      const dataFd = data.list[dataIdx];
      dataFd.setMoney = 0;
      setData({ ...data, list: data.list });
    }
  };

  const components = {
    body: {
      row: AxEditableFormRow,
      cell: AxEditableCellSimple,
    },
  };

  return (
    <AxModal
      showLoading={false}
      width="70%"
      handleVisible={handleVisible}
      handleCreate={handleCreate}
      {...rest}
      items={[
        <Row gutter={24}>
          <Search
            placeholder={placeholder ? placeholder : '搜索'}
            onSearch={val => handleSearch(val)}
            // style={{ width: '100%' }}
            allowClear
          />
          <Table
            bordered
            components={components}
            rowClassName={() => 'editable-row'}
            size="small"
            rowKey={record => record.id}
            checkboxModel={false}
            columns={columns}
            dataSource={data.list}
            loading={loading}
            scroll={{ x: 'max-content', y: 240 }}
            pagination={false}
            onRow={record => ({
              onClick: () => {
                if (handleClick) {
                  handleClick(record);
                }
              },
            })}
          />
          <Pagination
            size="small"
            style={{ float: 'right', marginTop: '5px' }}
            pageSize={page.pageSize}
            total={data.pagination.total}
            onChange={handlePageChange}
          />
        </Row>,
        <Row gutter={24}>
          <Table
            bordered
            size="small"
            rowKey={record => record.id}
            checkboxModel={false}
            columns={selectedColumns}
            dataSource={selectedData.list}
            scroll={{ x: 'max-content', y: 240 }}
            pagination={false}
            onRow={record => ({
              onDoubleClick: () => {
                handleRemoveSelectedData(record);
              },
            })}
          />
        </Row>,
      ]}
    />
  );
};

export default Form.create()(AxSelectOffset);
